package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.configer.ConfigHelper;
import com.warrior.entity.TicketEntity;
import com.warrior.entity.UserEntity;
import com.warrior.service.UserService;
import com.warrior.service.VerifyCodeService;
import com.warrior.util.CModelAndView;
import com.warrior.util.CommonUtils;
import com.warrior.util.ServerResponse;
import com.warrior.util.UploadUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户controller
 * Created by Shawn on 2017/3/15.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LogManager.getLogger(UserController.class.getName());

    @Autowired
    private UserService userService;

    @Autowired
    private VerifyCodeService verifyCodeService;


    /**
     * 保存一个用户
     *
     * @param userName 用户名
     * @param request  request
     * @param response response
     * @return String
     * @throws ProjectException 异常处理
     */
    @RequestMapping(value = "/saveUser", method = RequestMethod.GET)
    @ResponseBody
    public String saveUser(String userName, HttpServletRequest request, HttpServletResponse response) throws ProjectException {
        String userId = (String) request.getSession().getAttribute("userId");
        String returnMsg = null;
        try {
            this.userService.modifiedUserNickName(userId, userName);
            returnMsg = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            returnMsg = "failed";
            e.printStackTrace();
        }
        return returnMsg;
    }

    /**
     * 发送短信验证码
     *
     * @param mobile 手机号
     * @return String
     */
    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
    @ResponseBody
    public String sendMessage(String mobile) {
        this.verifyCodeService.sendVerifyCode(mobile);
        String returnMsg = null;
        try {
            returnMsg = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMsg;
    }


    /**
     * 修改用户头像
     *
     * @param request  request
     * @param response response
     * @return String
     */
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
    @ResponseBody
    public String uploadPic(HttpServletRequest request, HttpServletResponse response) {
        String returnMsg = null;
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        logger.debug("filePathName:" + saveFilePathName);
        Map map;
        String userId = (String) request.getSession().getAttribute("userId");
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    this.userService.modifiedUserPic(userId, savePath);
                    returnMsg = ServerResponse.okToJsonString("success");
                }
            }
        } catch (IOException | ProjectException e) {
            e.printStackTrace();
        }
        return returnMsg;
    }


    /**
     * 修改用户昵称
     *
     * @param request  request
     * @param response response
     * @param nickName 修改后的昵称
     * @return String (Status)
     */
    @RequestMapping(value = "/modifiedNickname",method = RequestMethod.POST)
    @ResponseBody
    public String modifiedUserNickName(HttpServletRequest request, HttpServletResponse response, String nickName) {
        String returnMsg = null;
        String userId = (String) request.getSession().getAttribute("userId");
        try {
            this.userService.modifiedUserNickName(userId, nickName);
            returnMsg = ServerResponse.okToJsonString("success");
        } catch (ProjectException | JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMsg;
    }


    /**
     * 验证手机页面路由
     *
     * @param request  request
     * @param response response
     * @return
     */
    @RequestMapping(value = "/verify_mobile")
    public ModelAndView validateMobile(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/user/verify", request, response);
        return mv;
    }

    /**
     * 发送验证码
     *
     * @param request  request
     * @param response response
     * @param mobile   手机号
     * @return
     */
    @RequestMapping(value = "/send_validate_code",method = RequestMethod.POST)
    @ResponseBody
    public String sendVerifyCode(HttpServletRequest request, HttpServletResponse response, String mobile) {
        String returnMsg = null;
        try {
            this.verifyCodeService.sendVerifyCode(mobile);
            returnMsg = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return returnMsg;
    }


    /**
     * 验证验证码
     *
     * @param request  request
     * @param response response
     * @param mobile   手机号
     * @param code     验证码
     * @return success / failed
     */
    @RequestMapping(value = "/validate_code",method = RequestMethod.POST)
    @ResponseBody
    public String validatedCode(HttpServletRequest request, HttpServletResponse response, String mobile, String code) {
        String returnMsg = null;
        try {
            boolean flag = this.verifyCodeService.validateVerifyCode(mobile, code);
            if (flag) {
                returnMsg = ServerResponse.okToJsonString("success");
            } else {
                returnMsg = ServerResponse.okToJsonString("failed");
            }
        } catch (ProjectException | JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMsg;
    }

    /**
     * 我的首页 路由
     *
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/my_account", method = RequestMethod.GET)
    public ModelAndView myAccount(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/user/user_center", request, response);
        String userId = (String) request.getSession().getAttribute("userId");
        UserEntity userEntity = this.userService.findUserById(userId);
        mv.addObject("userEntity", userEntity);
        return mv;
    }

    /**
     * 个人设置首页
     * @param request request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/user_setting",method = RequestMethod.GET)
    public ModelAndView userSetting(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new CModelAndView("warrior/user/user_setting",request,response);
        String userId = (String) request.getSession().getAttribute("userId");
        UserEntity userEntity = this.userService.findUserById(userId);
        mv.addObject("user",userEntity);
        return mv;
    }

    /**
     * 显示我的门票
     *
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/getMyTicket",method = RequestMethod.GET)
    public ModelAndView myTicket(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/ticket/my_tickets", request, response);
        String userId = (String) request.getSession().getAttribute("userId");
        //正常票务
        List<TicketEntity> ticketEntityList = this.userService.findAllTicketByUserId(userId, CommonUtils.String2Int("1"));
        mv.addObject("tickets", ticketEntityList);
        //过期票务
        List<TicketEntity> ticketEntities = this.userService.findAllTicketByUserId(userId, CommonUtils.String2Int("-1"));
        mv.addObject("expiredTicket",ticketEntities);
        return mv;
    }


    @RequestMapping(value = "/testUser",method = RequestMethod.POST)
    @ResponseBody
    public String testUser(String userId,HttpServletRequest request){
        request.getSession().setAttribute("userId",userId);
        return "success";
    }

    @RequestMapping(value = "/testUser",method = RequestMethod.GET)
    public ModelAndView testUser(HttpServletRequest request,HttpServletResponse response){
        ModelAndView mv = new CModelAndView("warrior/test",request,response);
        return mv;
    }

}
